import babelpolyfill from 'babel-polyfill'
import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui'
//import 'element-ui/lib/theme-default/index.css'
import './assets/theme/theme-test/index.css'
import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'
//import NProgress from 'nprogress'
//import 'nprogress/nprogress.css'
import routes from './routes'
// import Mock from './mock'
// Mock.bootstrap();
import 'font-awesome/css/font-awesome.min.css'
import './styles/vars.scss'
import Home from './views/Home.vue'

Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(Vuex)

//NProgress.configure({ showSpinner: false });

var router = new VueRouter({
  routes
})

function renderMenu(){
    var menu = JSON.parse(sessionStorage.getItem('menu'));
    if (menu) {  
        var menuRoutes = generateRoutes(menu);    
        menuRoutes.push({
            path: '*',
            hidden: true,
            redirect: { path: '/404' }
        });
        for(var i=0; i<menuRoutes.length; i++){
            router.options.routes.push(menuRoutes[i]);
        }
        router.addRoutes(menuRoutes);
        // registerRouteFresh = false;
    }
}
renderMenu();
let registerRouteFresh = true;
router.beforeEach((to, from, next) => {
    //NProgress.start();
    if (to.path == '/login') {
      sessionStorage.removeItem('user');
      sessionStorage.removeItem('menu');
    }
    let user = sessionStorage.getItem('user');
    if (!user && to.path != '/login') {
      next({ path: '/login' })
    } else {
      next()
    }
})

function generateRoutes(data){
    var routeArr = [];

    for(var i=0; i<data.length; i++){
        let routeObj = {};
        routeObj.name = data[i].label;
        routeObj.iconCls = data[i].iconCls;
        if(data[i].children && data[i].children.length > 0){
            routeObj.path = '/';
            routeObj.component = (resolve) => require(['./views/Home.vue'], resolve);
            routeObj.children = generateRoutes(data[i].children);
        }else{
            routeObj.path = data[i].path;
            routeObj.component = function(path){return (resolve) => require(['./views' + path + '.vue'], resolve);}(data[i].path)
        }

        routeArr.push(routeObj);
    }

    return routeArr;
}



//router.afterEach(transition => {
//NProgress.done();
//});

new Vue({
  //el: '#app',
  //template: '<App/>',
  router,
  store,
  //components: { App }
  render: h => h(App)
}).$mount('#app')


